package com.shaozi.nc.mq.substance;

import java.util.Set;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;

import com.shaozi.data.mq.business.base.SourceTypeConsts.OA.Quartz;
import com.shaozi.data.mq.business.bean.MQExchangeRuleBean;
import com.shaozi.data.mq.business.bean.MQPushItem;
import com.shaozi.data.mq.business.bus.substance.BasePushSubstanceHandler;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.bean.companyInfo.CompanyInfoUpdateBizBean;
import com.shaozi.nc.manage.CompanyInfoManager;
import com.shaozi.nc.mq.bean.quartz.QuartzBean;
import com.shaozi.nc.quartz.manage.ReportManage;
import com.shaozi.utils.common.JsonUtil;

public class QuartzPushSubstance extends BasePushSubstanceHandler {
	private final Logger logger = Logger.getLogger(QuartzPushSubstance.class);

	public QuartzPushSubstance() {
		super();
	}

	@Autowired
	private ReportManage reportManage;

	@Autowired
	private CompanyInfoManager companyInfoManager;

	@Override
	protected void onExchangeBiz(MQExchangeRuleBean pushData, MQPushItem pushItem, JSONObject jsonObj)
			throws SzException {
		switch (pushItem.getSourceType()) {
		case Quartz.Report_Quartz:
			reportJob(jsonObj);
			break;
		default:
			pushData.setBiz(null);
			break;
		}
	}

	private void reportJob(JSONObject jsonObj) {
		QuartzBean bizBean = null;
		try {
			bizBean = JsonUtil.toObject(jsonObj.getJSONObject("rule").get("biz").toString(), QuartzBean.class);
		} catch (SzException e1) {
			logger.error(e1.getMessage(), e1);
		} catch (JSONException e1) {
			logger.error(e1.getMessage(), e1);
		}
		if (bizBean == null || bizBean.getCompanyIds() == null || bizBean.getCompanyIds().length == 0) {
			Set<String> companyIds = companyInfoManager.getCompanyIdsWaitStartup();
			if (companyIds == null || companyIds.size() == 0) {
				return;
			}
			for (String companyId : companyIds) {
				reportJob(companyId);
			}
		} else {
			String[] comapnyIds = bizBean.getCompanyIds();
			for (String companyId : comapnyIds) {
				reportJob(companyId);
			}
		}

	}

	private void reportJob(String companyId) {
		try {
			reportManage.scheduleByConfig(companyId);
		} catch (SzException e) {
			logger.error(e.getMessage(), e);
		} catch (SchedulerException e) {
			logger.error(e.getMessage(), e);
		}
	}
}
